﻿using System.Windows;
using WPF.Core.Dtos;
using WPF.Core.Models;
using Prism.Ioc;


namespace WPF.Core.Services
{
    public class BaseService<T,F> where T : BaseModel where F : BaseTable
    {

        public BaseService()
        {
            //剑来 Prism.Ioc;
            mapper = ContainerLocator.Container.Resolve<IAppMapper>();
        }

        static Lazy<IFreeSql> sqliteLazy = new Lazy<IFreeSql>(() =>
        {
            var fsql = new FreeSql.FreeSqlBuilder()
                .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=freedb.db")
                .UseAutoSyncStructure(true)
                .Build();
            return fsql;
        });

        public readonly IAppMapper mapper;



        // 获取Sqlite实例
        public static IFreeSql Sqlite => sqliteLazy.Value;

        // 异步获取所有信息
        public async Task<List<T>> GetAll()
        {
            var model = await Sqlite.Select<F>()
                .ToListAsync();
            return mapper.Map<List<T>>(model);  
        }
        /// <summary>
        /// 根据Id获取
        /// </summary>
        public async Task<T> GetById(int id)
        {
            var model = await Sqlite.Select<F>().Where(q => q.Id == id).FirstAsync();
            return mapper.Map<T>(model);
        }

        // 创建
        public async Task Create(T input)
        {
            input.CreateTime = DateTime.Now;
            var model = mapper.Map<F>(input);
            var a = await Sqlite.Insert(model).ExecuteAffrowsAsync();
            if (a > 0) MessageBox.Show("添加成功"); 
        }

        // 删除
        public async Task Delete(int id)
        {
            // 根据学生id删除
            await Sqlite.Delete<F>().Where(s => s.Id == id).ExecuteAffrowsAsync();
        }

        // 更新
        public async Task Update(T input)
        {
            input.UpdateTime = DateTime.Now;
            var model = mapper.Map<F>(input);
            // 根据学生id更新
            var count =  await Sqlite.Update<F>().SetDto(model).
                                Where(s => s.Id == input.Id).ExecuteAffrowsAsync();   
            if (count > 0) MessageBox.Show("更新成功");
        }
    }
} 
